#include <iostream>
#include <vector>
#include <string>
#include <ctime>
#include <unistd.h>
#include <cassert>
#include <pthread.h>
using namespace std;
#include "Task.hpp"
#include "ringQueue.hpp"

string SelfName()
{
    char name[128];
    snprintf(name,sizeof name,"pthread[0x%x]",pthread_self());
    return name;
}

void* proctor_routine(void* args)
{
    ring_queue<Task>* rq = static_cast<ring_queue<Task>*>(args);
    while(true)
    {
        //测试代码
        // int data = rand()%10;
        // rq->push(data);
        // cout<<"生产者生产数据 "<< data <<endl;
        // sleep(1);//使其生产一个消费一个，看清现象
        
        //发送任务
        int x = rand()%10;
        int y = rand()%5;
        char op = str[rand()% str.size()];
        Task t(x,y,mymath,op);
        rq->push(t);
        cout<<"生产者: "<<SelfName()<<" 发送任务："<<t.ToString()<<endl;
        //sleep(1);
    }
}

void* consumer_routine(void* args)
{
    ring_queue<Task>* rq = static_cast<ring_queue<Task>*>(args);
    while(true)
    {
        // int data;
        // rq->pop(&data);
        // cout<<"消费者拿到数据 "<< data <<endl;
        Task t;
        rq->pop(&t);
        string result = t();
        cout<<"消费者: "<<SelfName()<<" 执行任务 "<<result<<endl;
    }
}
int main()
{
    srand((unsigned int)time(nullptr) ^ getpid()); //生产随机数，并使其更乱一些
    ring_queue<Task>* rq = new ring_queue<Task>();
    //多生产消费的环境
    pthread_t p[4],c[8];
    for(int i = 0;i<4;++i)
    {
        pthread_create(p+i,nullptr,proctor_routine,rq);
    }
    for(int i = 0;i<8;++i)
    {
        pthread_create(c+i,nullptr,consumer_routine,rq);
    }

    //线程回收
    for(int i = 0;i<4;++i)
    {
        pthread_join(p[i],nullptr);
    }
    for(int i = 0;i<8;++i)
    {
        pthread_join(c[i],nullptr);
    }


    // pthread_t p,c;//生产者和消费者
    // ring_queue<Task>* rq = new ring_queue<Task>();
    // pthread_create(&p,nullptr,proctor_routine,(void*)rq);
    // pthread_create(&p,nullptr,consumer_routine,(void*)rq);

    // pthread_join(p,nullptr);
    // pthread_join(c,nullptr);
    return 0;
}